package com.zzy.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.edu.entity.EduSubject;
import com.zzy.edu.entity.vo.excel.SubjectData;
import com.zzy.edu.entity.vo.subject.OneSubject;
import com.zzy.edu.entity.vo.subject.TwoSubject;
import com.zzy.edu.listenr.SubjectExcelLister;
import com.zzy.edu.mapper.EduSubjectMapper;
import com.zzy.edu.service.EduSubjectService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author KAZU
 * @since 2023-01-11
 */
@SuppressWarnings("all")
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
	
	@Autowired
	private EduSubjectMapper subjectMapper;
	
	/**
	 * 添加课程分类
	 * */
	@Override
	public void saveSubject(MultipartFile file, EduSubjectService subjectService) throws IOException {
		// 文件输入流
		InputStream in = file.getInputStream();
		// 调用方法进行读取
		EasyExcel.read(in, SubjectData.class, new SubjectExcelLister(subjectService)).sheet().doRead();
	}
	
	@Override
	public List<OneSubject> getAllOneTwoSubject() {
		// 先查询一级分类
		QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
		wrapperOne.eq("parent_id", "0");
		List<EduSubject> oneSubjectList = subjectMapper.selectList(wrapperOne);
		// 查询二级分类
		QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
		wrapperTwo.ne("parent_id", "0");
		List<EduSubject> twoSubjectList = subjectMapper.selectList(wrapperTwo);
		// 创建list集合，储存最终封装数据
		List<OneSubject> finalSubjectList = new ArrayList<>();
		// 封装一级分类
		for (EduSubject subject1 : oneSubjectList) {
			// 把eduSubject里面的值取出来，放到oneSubject中，再把oneSubject放到finalSubjectList
			OneSubject oneSubject = new OneSubject();
			/*oneSubject.setId(subject.getId());
			oneSubject.setTitle(subject.getTitle());*/
			BeanUtils.copyProperties(subject1, oneSubject);
			finalSubjectList.add(oneSubject);
			/**
			 * 在一级分类循环遍历查询所有的二级分类
			 * 创建list集合封装每个一级分类的二级分类
			 * */
			List<TwoSubject> twofinalSubjectList = new ArrayList<>();
			for (EduSubject subject2 : twoSubjectList) {
				// 判断二级分类的parentId和一级分类的id是否相同
				if(subject2.getParentId().equals(subject1.getId())) {
					// 把subject2放在TwoSubject里面，在放在twofinalSubjectList
					TwoSubject twoSubject = new TwoSubject();
					BeanUtils.copyProperties(subject2, twoSubject);
					twofinalSubjectList.add(twoSubject);
				}
			}
			// 把二级封装后的集合封装到一级的children中
			oneSubject.setChildren(twofinalSubjectList);
		}
		// 封装二级分类
		
		return finalSubjectList;
	}
}
